import React, { useEffect, useRef, useState } from 'react';
import { Modal, Popover, Input, Button, message } from 'antd';
import { SendOutlined, UserOutlined } from '@ant-design/icons';
import { Link } from 'react-router-dom';

import { urlMap } from '@/utils';
import { ReactComponent as RobotIcon } from '@/assets/images/icons/RobotIcon.svg';
import { ReactComponent as SendPriIcon } from '@/assets/images/icons/SendPriIcon.svg';
import './index.scss';

export default function AssistantDialog({ visible, onClose, position }) {
    const [inputMsg, setInputMsg] = useState('');
    const [messages, setMessages] = useState([
        // { role: 'assistant', content: '您好！我是您的智能助手小韵，有什么可以帮您？' }
        { role: 'assistant', content: '您好！这里是智能助手页面！' },
    ]);
    const [isResponding, setIsResponding] = useState(false);
    const messagesEndRef = useRef(null);
    const sseRef = useRef(null);
    useEffect(() => {
        return () => {
            if (sseRef.current) {
                sseRef.current.close();
            }
        };
    }, []);

    const handleSend = async () => {
        if (!inputMsg.trim()) return;

        // 添加用户消息
        const newUserMessage = { role: 'user', content: inputMsg };
        setMessages((prev) => [...prev, newUserMessage]);
        setInputMsg('');

        // 添加初始助手响应
        const initialBotMessage = { role: 'assistant', content: '▌' };
        setMessages((prev) => [...prev, initialBotMessage]);
        setIsResponding(true);

        try {
            const sse = new EventSource(`${urlMap.defaultUrl}/ai/chat?message=${encodeURIComponent(inputMsg)}`);
            sseRef.current = sse;
            const abortController = new AbortController();
            sse.onmessage = (e) => {
                const chunk = e.data.trim();
                if (!chunk) return; // 过滤空数据

                if (chunk === '[complete]') {
                    setMessages((prev) => {
                        const lastMsg = prev[prev.length - 1];
                        if (!lastMsg) return prev;
                        return [...prev.slice(0, -1), { ...lastMsg, content: lastMsg.content.slice(0, -1) }];
                    });
                    sse.close();
                    setIsResponding(false);
                } else {
                    setMessages((prev) => {
                        const lastMsg = prev[prev.length - 1];
                        if (!lastMsg) return prev;
                        return [
                            ...prev.slice(0, -1),
                            {
                                ...lastMsg,
                                content: lastMsg.content.slice(0, -1) + chunk + '▌',
                            },
                        ];
                    });
                }
            };

            sse.onerror = () => {
                sse.close();
                setIsResponding(false);
                message.error('连接异常，请稍后重试');
            };

            // 浏览器关闭时清理
            window.addEventListener('beforeunload', () => sse.close());
        } catch (error) {
            message.error('请求失败: ' + error.message);
            setIsResponding(false);
        }
    };

    // 保持自动滚动到底部
    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    };

    useEffect(() => {
        scrollToBottom();
    }, [messages]);
    return (
        <Modal
            title="智能助手"
            open={visible}
            onCancel={onClose}
            footer={null}
            mask={false}
            maskClosable
            width={400}
            style={{
                minHeight: 600,
                maxHeight: '80vh',
                position: 'fixed',
                top: '6vh',
                left: 'calc(100% - 440px)',
                transition: 'all 0.3s',
                overflow: 'hidden',
            }}
        >
            <div
                style={{
                    height: '100%',
                    display: 'flex',
                    flexDirection: 'column',
                }}
            >
                <div
                    className="custom-scrollbar"
                    style={{
                        minHeight: 360,
                        maxHeight: '55vh',
                        overflowY: 'auto',
                        paddingRight: 5,
                        marginBottom: 16,
                        position: 'relative',
                        zIndex: 0,
                    }}
                >
                    {messages.map((msg, index) => (
                        <div
                            key={index}
                            style={{
                                display: 'flex',
                                gap: 5,
                                flexDirection: msg.role === 'user' ? 'row-reverse' : 'row',
                                marginBottom: 16,
                            }}
                        >
                            {/* 头像 */}
                            <div
                                style={{
                                    width: 36,
                                    height: 36,
                                    borderRadius: '50%',
                                    background: msg.role === 'user' ? '#1890ff' : '#f0f5ff',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                }}
                            >
                                {msg.role === 'user' ? (
                                    <UserOutlined style={{ color: 'white' }} />
                                ) : (
                                    <RobotIcon style={{ width: 24, height: 24 }} />
                                )}
                            </div>

                            {/* 消息内容 */}
                            <div style={{ maxWidth: '70%' }}>
                                <div
                                    style={{
                                        color: '#666',
                                        fontSize: 12,
                                        // fontFamily: "'STXingkai', cursive",
                                        marginBottom: 2,
                                        marginRight: 3,
                                        marginTop: -2,
                                    }}
                                >
                                    {msg.role === 'user' ? '我' : '小韵'}
                                </div>
                                <div
                                    style={{
                                        background: msg.role === 'user' ? '#1890ff' : '#f0f5ff',
                                        color: msg.role === 'user' ? 'white' : '#333',
                                        padding: '8px 12px',
                                        borderRadius: 12,
                                        whiteSpace: 'pre-wrap',
                                        wordBreak: 'break-word',
                                        lineHeight: 1.6,
                                    }}
                                >
                                    {msg.content
                                        .split(/(\[.*?\]\(\/cultPop\/\d+\)|https?:\/\/[^\s]+)/g)
                                        .map((part, i) => {
                                            const mdLinkMatch = part.match(/\[(.*?)\]\(\/cultPop\/(\d+)\)/);
                                            if (mdLinkMatch) {
                                                return (
                                                    <Link
                                                        key={i}
                                                        to={`/cultPop/${mdLinkMatch[2]}`}
                                                        style={{
                                                            color: msg.role === 'user' ? '#fff' : '#1890ff',
                                                            textDecoration: 'underline',
                                                            padding: '0 2px',
                                                        }}
                                                    >
                                                        {mdLinkMatch[1]}
                                                    </Link>
                                                );
                                            } else if (part.match(/^https?:\/\//)) {
                                                return (
                                                    <a
                                                        key={i}
                                                        href={part}
                                                        target="_blank"
                                                        rel="noopener noreferrer"
                                                        style={{
                                                            color: msg.role === 'user' ? '#fff' : '#1890ff',
                                                            textDecoration: 'underline',
                                                            padding: '0 2px',
                                                        }}
                                                    >
                                                        {part}
                                                    </a>
                                                );
                                            }
                                            return <span key={i}>{part}</span>;
                                        })}
                                </div>
                            </div>
                        </div>
                    ))}
                    <div ref={messagesEndRef} style={{ height: 1 }} />
                </div>

                <div
                    style={{
                        position: 'relative',
                        padding: '3px 0',
                        borderTop: '1px solid #f0f0f0',
                        zIndex: 1,
                    }}
                >
                    <Input.TextArea
                        autoSize={{ minRows: 3, maxRows: 4 }}
                        value={inputMsg}
                        onChange={(e) => setInputMsg(e.target.value)}
                        onPressEnter={handleSend}
                        placeholder="请输入您的问题..."
                        style={{
                            borderRadius: 5,
                            // fontFamily: "'STXingkai', cursive",
                            padding: '8px 45px 8px 16px',
                            width: '100%',
                        }}
                    />
                    <Button
                        type="line"
                        icon={
                            <SendPriIcon
                                style={{
                                    width: 26,
                                    height: 26,
                                }}
                            />
                        }
                        onClick={handleSend}
                        style={{
                            position: 'absolute',
                            right: 8,
                            bottom: 16,
                            height: 36,
                            width: 36,
                            borderRadius: '50%',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                        }}
                    />
                </div>
            </div>
        </Modal>
    );
}
